package top.linyuxb.lycloud.common.utils;

import cn.hutool.system.SystemUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Intellij IDEA.
 *
 * @Author: linyuxb
 * @Date: 2024/7/2 18:15
 * @Desc: 网络工具
 */
@Slf4j
public class InetAddressUtil {
    /**
     * ip地址存储
     */
    private static final List<String> ipAddressList = new ArrayList<>();

    /**
     * 获取ip地址
     *
     * @param registerType
     * @return
     */
    public static String getIpAddress(Integer registerType) {
        if (!ipAddressList.isEmpty()) {
            return ipAddressList.get(0);
        }
        String address = SystemUtil.getHostInfo().getAddress();
        if (registerType == 2) {
            address = getPublicAddress();
        }
        ipAddressList.add(0, address);
        return address;
    }

    /**
     * 获取公网地址 服务需要可联网
     *
     * @return
     */
    public static String getPublicAddress() {
        // 使用AWS的服务获取外网IP
        String ipFetchUrl = "http://checkip.amazonaws.com";
        try {
            URL url = new URL(ipFetchUrl);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            // 也可以使用其他的HTTP方法，如GET或POST
            con.setRequestMethod("GET");
            // 发起请求
            int responseCode = con.getResponseCode();
            // 如果请求成功
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                String address = response.toString();
                // 打印外网IP
                log.info("External IP: " + address);
                return address;
            } else {
                log.info("GET request not worked");
            }
        } catch (Exception e) {
            log.error("InetAddressUtil getPublicAddress error", e);
        }
        return "";
    }
}
